'use client'

import * as z from 'zod'
import { useForm } from "react-hook-form"
import { useState, useTransition } from 'react'
import { zodResolver } from "@hookform/resolvers/zod"

import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import FormError from '@/components/form-error'
import FormSuccess from '@/components/form-success'
import CardWrapper from "@/components/auth/card-wrapper"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage
} from '@/components/ui/form'

import { reset } from '@/actions/reset'
import { ResetSchema } from '@/schemas/auth'

const ResetForm = () => {
    const [error, setError] = useState<string | undefined>('')
    const [success, setSuccess] = useState<string | undefined>('')
    const [isPending, startTransition] = useTransition()

    const form = useForm<z.infer<typeof ResetSchema>>({
        resolver: zodResolver(ResetSchema),
        defaultValues: { email: '' }
    })

    const handleSubmit = (values: z.infer<typeof ResetSchema>) => {
        setError('')
        setSuccess('')

        startTransition(() => {
            reset(values).then(data => {
                setError(data.error)
                setSuccess(data.success)
            })
        })
    }

    return (
        <CardWrapper
            headerLabel="Forget your password?"
            backButtonLabel="Back to login"
            backButtonPath="/auth/login"
        >
            <Form {...form}>
                <form
                    onSubmit={form.handleSubmit(handleSubmit)}
                    className='space-y-6'
                >
                    <div className='space-y-4'>
                        <FormField
                            control={form.control}
                            name='email'
                            render={(({ field, fieldState }) => (
                                <FormItem>
                                    <FormLabel htmlFor='email'>邮箱</FormLabel>
                                    <FormControl>
                                        <Input {...field} disabled={isPending} placeholder='name@example.com' type='email' />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            ))}
                        />
                    </div>
                    <FormError message={error} />
                    <FormSuccess message={success} />
                    <Button disabled={isPending} type='submit' className='w-full'>发送重置邮件</Button>
                </form>
            </Form>
        </CardWrapper >
    )
}

export default ResetForm